//  SingRecordFinshView.m
//  CCBbelefitLife
//  Created by liurg on 16/1/12.
//  Copyright © 2016年 liurg. All rights reserved.
#import "SingRecordFinshView.h"
#import "LocalRecordViewCtr.h"
#import <AudioToolbox/AudioToolbox.h>
#import "lame.h"
#import "Utilities.h"
#import "CustomPickerBottomView.h"

#define  DocRecordPath  @"docRecordPath"

@interface SingRecordFinshView ()
{
    EQModel *eqModel;
    NSString * musicPath;
    UIScrollView *scrollView;
    UIImageView *playImgView;
}
@property(nonatomic,retain) UISlider *progressSlider;

@property(nonatomic,assign) BOOL isPlay;
@property(nonatomic,retain) AVAudioPlayer *audioPlayRec;
@property(nonatomic,retain) NSTimer *playTimer;
@property(nonatomic,retain) UILabel *startTimeLab;
@property(nonatomic,retain) UILabel *endTimeLab;
@property(nonatomic,strong) NSArray *eqValueArray;
@property(nonatomic,retain) NSString *docRecordTruePath;
@property(nonatomic,retain) NSString *SelectStyle;


@end
@implementation SingRecordFinshView
- (id)initWithPlayer:(EQPlayer *)eqplayer
{
    self = [super init];
    if (self) {
        player = eqplayer;
        player.delegate = self;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"K歌";
    seleArray = [NSMutableArray arrayWithCapacity:1];
    [self SetupView];
    self.SelectStyle = @"0";
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
     self.tabBarController.tabBar.hidden = YES;
    [player stopAUGraph];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [player stopAUGraph];
    player = nil;
    player.delegate = nil;
}


-(void)SetupView{
    
    UIImageView *backViewImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth, mainScreenHeight-64)];
    backViewImg.image = [UIImage imageNamed:@"清唱背景"];
    [self.view addSubview:backViewImg];
    UIButton *recordMaiBtn = [[UIButton alloc]initWithFrame:CGRectMake(70, 70, mainScreenWidth-70*2, mainScreenWidth-75*2)];
    [self.view addSubview:recordMaiBtn];
    [recordMaiBtn setBackgroundImage:[UIImage imageNamed:@"cd"] forState:UIControlStateNormal];
    // [recordMaiBtn addTarget:self action:@selector(recordSingMusic:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView  *playBackView = [[UIView alloc]initWithFrame:CGRectMake(0, mainScreenHeight-50-120-64-50, mainScreenWidth, 50)];
    playBackView.backgroundColor = JYColor(128, 109, 100);
    [self.view addSubview:playBackView];
    UIButton *playBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 15, 40, 40)];
    [playBtn addTarget:self action:@selector(playRecordMusic) forControlEvents:UIControlEventTouchUpInside];
    [playBackView addSubview:playBtn];
    playImgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 0, 20 , 20)];
    playImgView.image = [UIImage imageNamed:@"多边形-1"];
    [playBtn addSubview:playImgView];
    
    UILabel *startTimeLab = [[UILabel alloc]initWithFrame:CGRectMake(playBtn.righX+5, 15, 50, 20)];
    startTimeLab.text = @"00:00";
    startTimeLab.font = [UIFont systemFontOfSize:14];
    startTimeLab.textColor = [UIColor whiteColor];
    _startTimeLab = startTimeLab;
    [playBackView addSubview:startTimeLab];
    
    _progressSlider = [[UISlider alloc] initWithFrame:CGRectZero];
    _progressSlider.frame = CGRectMake(startTimeLab.righX+5, 15, mainScreenWidth-60-startTimeLab.righX-5, 20);
    // [_progressSlider setThumbImage:[UIImage imageNamed:@"sliderThumb_small.png"] forState:UIControlStateNormal];
    _progressSlider.thumbTintColor=JYColor(233, 131, 46);
    _progressSlider.tag = 106;
    //设置已经滑过一端滑动条背景图片，会覆盖之前之前的颜色，以下相同
    _progressSlider.minimumTrackTintColor=JYColor(105, 215, 16);
    //设置未滑过一端滑动条颜色
    _progressSlider.maximumTrackTintColor=JYColor(246, 246, 246);
    [_progressSlider addTarget:self action:@selector(progressPlayChange:)
              forControlEvents:UIControlEventValueChanged];
    _progressSlider.minimumValue = 0.0f;
    _progressSlider.maximumValue = 10.0f;
    _progressSlider.value = 0.0f;
    [playBackView addSubview:_progressSlider];
    
    UILabel *endTimeLab = [[UILabel alloc]initWithFrame:CGRectMake(_progressSlider.righX+5, 15, 50, 20)];
    endTimeLab.text = @"00:00";
    endTimeLab.font = [UIFont systemFontOfSize:14];
    endTimeLab.textColor = [UIColor whiteColor];
    _endTimeLab = endTimeLab;
    [playBackView addSubview:endTimeLab];
    
    UIImageView *bottomImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, mainScreenHeight-50-120-64, mainScreenWidth, 120)];
    bottomImg.image = [UIImage imageNamed:@"qc_bgbottom"];
    [self.view addSubview:bottomImg];
    
    scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, bottomImg.y, mainScreenWidth, bottomImg.height)];
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.scrollEnabled = YES;
    scrollView.bounces = NO;
    scrollView.alwaysBounceHorizontal = NO;
    scrollView.alwaysBounceVertical = NO;
    [self.view addSubview:scrollView];
    
    NSArray *imgArr = [NSArray arrayWithObjects:@[@"qc_yaunsheng",@"qc_shili",@"qc_yg"],@[@"qc_yaunsheng" ,@"qc_yaunsheng",@"qc_shili"],@ [@"qc_yg",@"qc_shili",@"qc_yg"],nil];
    NSArray *desNameArr = [NSArray arrayWithObjects:@[@"留原声",@"流行",@"重低音"],@[@"人声",@"摇滚",@"古典"],@[@"爵士",@"舞曲",@"电子"], nil];
    _eqcount = 1;
    NSInteger n = 0;
    for(NSInteger j = 0 ; j<3;j++){
        for (NSInteger i = 0; i<3; i++) {
            
            UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(i*60+(i+1)*(mainScreenWidth-60*3)/4+j*mainScreenWidth, 20, 60, 60)];
            imgView.image = [UIImage imageNamed:imgArr[j][i]];
            [scrollView addSubview:imgView];
            
            UIImageView * seleImgView = [[UIImageView alloc]initWithFrame:imgView.frame];
            if(i == 1 && j == 0){
                seleImgView.hidden = NO;
            }else{
                seleImgView.hidden = YES;
            }
            seleImgView.image = [UIImage imageNamed:@"choose@2x.png"];
            [seleArray addObject:seleImgView];
            [scrollView addSubview:seleImgView];
            
            UILabel *desLab = [[UILabel alloc]initWithFrame:CGRectMake(imgView.x, imgView.bottomY+5, imgView.width, 20)];
            desLab.text = desNameArr[j][i];
            desLab.textColor = [UIColor whiteColor];
            desLab.font = [UIFont systemFontOfSize:14];
            desLab.textAlignment = NSTextAlignmentCenter;
            [scrollView addSubview:desLab];
            
            UIControl * imgControl = [[UIControl alloc]initWithFrame:CGRectMake( mainScreenWidth/3*i+(j*mainScreenWidth),0,mainScreenWidth/3.0, bottomImg.height )];
            imgControl.tag = n;
            [imgControl addTarget:self action:@selector(cutMusicSize:) forControlEvents:(UIControlEventTouchUpInside)];
            [scrollView addSubview:imgControl];
            n++;
        }
    }
    scrollView.contentOffset=CGPointMake(0, 0);
    //不能半页停 必整页滚动
    scrollView.pagingEnabled=YES;
    scrollView.contentSize = CGSizeMake(mainScreenWidth*3.0, 0);
    
    //构建底部栏
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, mainScreenHeight-50-64, mainScreenWidth, 50)];
    bottomView.backgroundColor = JYColor(238, 239, 241);
    [self.view addSubview:bottomView];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0, 10, 1, 30)];
    lineView.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:lineView];
    
    UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0*2, 10, 1, 30)];
    lineView1.backgroundColor = [UIColor grayColor];
    [bottomView addSubview:lineView1];
    
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:leftBtn];
    [leftBtn addTarget:self action:@selector(saveLeftBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *flowerImg = [[UIImageView alloc]initWithFrame:CGRectMake((leftBtn.width-20)/2, 15, 20, 20)];
    flowerImg.image = [UIImage imageNamed:@"qc_flower"];
    [leftBtn addSubview:flowerImg];
    
    UIButton *middleBtn = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:middleBtn];
    [middleBtn addTarget:self action:@selector(saveRecordBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UILabel *desLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 15, middleBtn.width, 20)];
    desLab.textAlignment = NSTextAlignmentCenter;
    desLab.text = @"保存录音";
    [middleBtn addSubview:desLab];
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenWidth/3.0*2, 0, mainScreenWidth/3.0, 50)];
    [bottomView addSubview:rightBtn];
    //  [rightBtn addTarget:self action:@selector(ringingBellBtnAction) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *bellImg = [[UIImageView alloc]initWithFrame:CGRectMake((rightBtn.width-20)/2, 15, 20, 20)];
    bellImg.image = [UIImage imageNamed:@"ringingBell"];
    [rightBtn addSubview:bellImg];
    
}

- ( void ) viewWillAppear:( BOOL ) animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:NO];
  //  [AppDelegate ShowTabarView:NO];
    [self buildNavView];
    // [ShareAppDelegate.ApptabBar hideSysTabar];
}

-(void)buildNavView{
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"" highIcon:@"" target:self action:nil];
}

-(void)backBtnAction{
    
    [player stopAUGraph];
    
    [[NSFileManager defaultManager]removeItemAtPath:_recordMusicPath error:nil];
    [self.navigationController popViewControllerAnimated:YES];
    //  [[UIApplication sharedApplication] setStatusBarHidden:NO];
}

-(void)playRecordMusic{
    if (player.isPlaying == YES) {
        [player stopAUGraph];
        playImgView.image = [UIImage imageNamed:@"music_stop@2x.png"];
        return ;
    }
    playImgView.image = [UIImage imageNamed:@"多边形-1.png"];
    frequency = [player getFrequencyBand];
    [player setFileName:_recordMusicPath];
    int m = player.duration / 60;
    int s = ((int) player.duration) % 60;
    _endTimeLab.text = [NSString stringWithFormat:@"%.2d:%.2d", m, s];
    eqModel = [[EQModel alloc]init];
    _eqValueArray = [eqModel eqValueFromIndex:_eqcount];
    player.delegate = self;
    for (int i=0; i<[frequency count]; i++) {
        [player setEQ:i gain:[_eqValueArray[i] floatValue]];
    }
    
}


- (void)updateCurrentTime:(float)time
{
    dispatch_async(dispatch_get_main_queue(), ^{

        _progressSlider.maximumValue = player.duration;
        int m = time / 60;
        int s = ((int)time)% 60;
        _startTimeLab.text = [NSString stringWithFormat:@"%.2d:%.2d", m, s];

        _progressSlider.minimumValue = 0;
        _progressSlider.value = time;
        
    });
}

//切换音频
-(void)cutMusicSize:(UIControl *)sender{

    seleEq = sender.tag;
    for(int i = 0;i< seleArray.count;i++){
        
        if(i == sender.tag){
            ((UIImageView *)seleArray[i]).hidden = NO;
        }else{
            ((UIImageView *)seleArray[i]).hidden = YES;
        }
    }
    _eqcount = seleEq;
    _eqValueArray = [eqModel eqValueFromIndex:_eqcount];
    for (int i=0; i<[frequency count]; i++) {
        [player setEQ:i gain:[_eqValueArray[i] floatValue]];
    }

}

- (void) convertToMp3
{
    // NSURL *recordedFileNameUrl = [NSURL fileURLWithPath:recordedFileName];
    @try {
        int read, write;
        
        FILE *pcm = fopen([_recordMusicPath cStringUsingEncoding:1], "rb");  //source
        if(pcm == NULL){
            return;
        }
        fseek(pcm, 4*1024, SEEK_CUR);
        //skip file header
        FILE *mp3 = fopen([musicPath cStringUsingEncoding:1], "wb");  //output
        if(mp3 == NULL){
            return;
        }
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 44100.0);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {

    }
    
}

//保存录音
-(void)saveRecordBtnAction{
    [player stopAUGraph];
    player = nil;
    player.delegate = nil;
    
    //判断是哪一种录音－－纯录音－－跟歌曲录音
    if (_recordMusicName.length > 1) {
        
        LocalRecordViewCtr * localRecordViewCtr = [[LocalRecordViewCtr alloc]init];
        [self.navigationController pushViewController:localRecordViewCtr animated:YES];
    }
    else
    {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入录音名字" message:@"" delegate:self cancelButtonTitle:@"添加" otherButtonTitles:@"取消",nil];
        [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
        [dialog textFieldAtIndex:0].placeholder = @"请输入录音名字不要超过10个字";
        [dialog show];
    }
}

-(void)alertView : (UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0){
        //输入的名字
        UITextField * recordName = [alertView textFieldAtIndex:0];
        musicPath = [Utilities getDocmentSaveFilePathString:recordName.text filePath:DocRecordPath];
        [self convertToMp3];
        [[NSFileManager defaultManager] removeItemAtPath:_recordMusicPath error:nil];
        LocalRecordViewCtr * localRecordViewCtr = [[LocalRecordViewCtr alloc]init];
        localRecordViewCtr.recordMusicPath  = _recordMusicPath;
        [self.navigationController pushViewController:localRecordViewCtr animated:YES];
    }
}

-(void)saveLeftBtnAction{
    
}

-(void)progressPlayChange:(UISlider *)progressSlider{
    
}

-(void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
